package com.yf.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.Utils.CacheKey;
import com.yf.Utils.RedisUtils;
import com.yf.dao.DictDetailMapper;
import com.yf.dao.DictMapper;
import com.yf.domain.dict.Dict;
import com.yf.domain.dict.DictDetail;
import com.yf.model.query.DictDetailQueryCriteria;
import com.yf.modules.system.service.api.DictDetailService;
import com.yf.response.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @author chentianwei
 * @date 2024-10-14 17:45
 * @description 词典明细业务实现层
 */
@Service
@Slf4j
public class DictDetailServiceImpl extends ServiceImpl<DictDetailMapper, DictDetail> implements DictDetailService {

    private final DictDetailMapper dictDetailMapper;
    private final RedisUtils redisUtils;
    private final DictMapper dictMapper;

    public DictDetailServiceImpl(DictDetailMapper dictDetailMapper,
                                 RedisUtils redisUtils,
                                 DictMapper dictMapper) {
        this.dictDetailMapper = dictDetailMapper;
        this.redisUtils = redisUtils;
        this.dictMapper = dictMapper;
    }

    /**
     * 查询DictDetail
     *
     * @param criteria 查询条件
     * @return 字典数据集合
     */
    @Override
    public List<DictDetail> queryDictDetail(DictDetailQueryCriteria criteria) {
        return dictDetailMapper.findAll(criteria);
    }

    /**
     * 添加新的字典明细
     *
     * @param entity 实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDictDetail(DictDetail entity) {
        if (entity.getId() != null) {
            throw new BusinessException("此数据已存在，不允许添加");
        }
        entity.setDictId(entity.getDict().getId());
        save(entity);
        // 清理缓存
        delCaches(entity);
    }

    /**
     * 修改字典明细
     *
     * @param entity 实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editDictDetail(DictDetail entity) {
        DictDetail dictDetail = getById(entity.getId());
        entity.setId(dictDetail.getId());
        // 更新数据
        saveOrUpdate(entity);
        // 清理缓存
        delCaches(dictDetail);
    }

    /**
     * 删除字典明细
     *
     * @param ids 主键
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDictDetail(Set<Long> ids) {
        for (Long id : ids) {
            DictDetail dictDetail = getById(id);
            removeById(id);
            // 清理缓存
            delCaches(dictDetail);
        }
    }

    public void delCaches(DictDetail dictDetail) {
        Dict dict = dictMapper.selectById(dictDetail.getDictId());
        redisUtils.del(CacheKey.DICT_NAME + dict.getName());
    }
}
